//
//  YWAllMyPostTroublesTableViewController.m
//  maintain
//
//  Created by 烟雨云渊 on 17/1/4.
//  Copyright © 2017年 ewin. All rights reserved.
//

#import "YWAllMyPostTroublesTableViewController.h"
#import "UIColor+CustomColors.h"
#import "UIScrollView+EmptyDataSet.h"
#import "NSDate+YYAdd.h"
#import "MJRefresh.h"
#import "YWMacro.h"
#import "YWConst.h"
#import "YWCommonTool.h"

#import "UITableView+FDTemplateLayoutCell.h"
#import "YWMyPostTroubleCell.h"

#import "YWMission.h"

#import "YWMissionManager.h"
#import "YWCirculationDetailViewController.h"
#import "YWEwinManager.h"
//#import "YWReplyManager.h"
//#import "YWNoReadReplyTableViewController.h"
#import "YWReportTroubleManager.h"
#import "YWReportTroubleModel.h"

@interface YWAllMyPostTroublesTableViewController ()<DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>{
    NSInteger page;
}
@property (nonatomic, strong) NSArray *dataSource;
@end

@implementation YWAllMyPostTroublesTableViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor customBackgroudColor];
    
    [self setupNotifications];
    [self setupTableView];
}

- (void)setupNotifications{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView:) name:KPostRefreshCirculationDetailVCNoti object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTableView:) name:KPostCirculationHandlerNotification object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(refreshTop) name:KPostNoQrcodePostTroubleNotification object:nil];
}

- (void)setupTableView{
    page = 1;
    [self.tableView registerClass:[YWMyPostTroubleCell class] forCellReuseIdentifier:YWMyPostTroubleCellIdentifier];
    self.tableView.backgroundColor = [UIColor customBackgroudColor];
    self.tableView.sectionFooterHeight = 1.0;
    self.tableView.tableFooterView = [[UIView alloc] init];
    self.tableView.contentInset = UIEdgeInsetsMake(0, 0, KbottomViewH, 0);
    self.tableView.estimatedRowHeight = 44.0f;
    self.tableView.rowHeight = UITableViewAutomaticDimension;
    
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshTop)];
    self.tableView.mj_footer = [MJRefreshBackNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(refreshFootor)];
    self.tableView.mj_footer.automaticallyHidden = YES;
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
    
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;
}

- (void)refreshTableView:(id)sender{
    _dataSource = nil;
    [self.tableView reloadData];
}

- (NSArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSArray alloc] initWithArray:[[YWReportTroubleManager shareManager] getMyReportTroubleWithPage:page]];
        //[self getreportTroubleMinCreateTime];
    }
    return _dataSource;
}

#pragma mark - UITableViewDataSource mothods
- (NSInteger)numberOfSectionsInTableView:(UITableView*)tableView
{
    return [self.dataSource  count];
}

- (NSInteger)tableView:(UITableView*)tableView numberOfRowsInSection:(NSInteger)section
{
    return [self.dataSource[section]  count];
}

#pragma mark - UITableViewDelegate mothods

//- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
//    return [tableView fd_heightForCellWithIdentifier:YWMyPostTroubleCellIdentifier cacheByIndexPath:indexPath configuration:^(YWMyPostTroubleCell *cell) {
//        cell.fd_enforceFrameLayout = NO;
//        cell.reportTrouble = self.dataSource[indexPath.section][indexPath.row];
//    }];
//}

- (UITableViewCell*)tableView:(UITableView*)tableView cellForRowAtIndexPath:(NSIndexPath*)indexPath
{
    YWMyPostTroubleCell *cell = [tableView dequeueReusableCellWithIdentifier:YWMyPostTroubleCellIdentifier];
    cell.reportTrouble = self.dataSource[indexPath.section][indexPath.row];
    return cell;
}

#pragma mark - UITableViewDataDelegate mothods

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    YWCirculationDetailViewController *circulationDetailVC = [[YWCirculationDetailViewController alloc] init];
    YWReportTroubleModel *reportTrouble = self.dataSource[indexPath.section][indexPath.row];
    circulationDetailVC.troubleMissionModel = reportTrouble.troubleMission;
    [self.navigationController pushViewController:circulationDetailVC animated:YES];
}

- (CGFloat)tableView:(UITableView*)tableView heightForHeaderInSection:(NSInteger)section{
    return 35;
}

#pragma mark - table view section header view
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    static NSString* HeaderIdentifier = @"YWUnAssignPostTroubleTableViewControllerForHeaderInSection";
    UITableViewHeaderFooterView* headerView = [tableView dequeueReusableHeaderFooterViewWithIdentifier:HeaderIdentifier];
    if (headerView == nil) {
        headerView = [[UITableViewHeaderFooterView alloc] initWithReuseIdentifier:HeaderIdentifier];
        headerView.contentView.backgroundColor = [UIColor customBackgroudColor];
        UILabel* label = [[UILabel alloc] init];
        label.textAlignment = NSTextAlignmentLeft;
        label.textColor = [UIColor blackColor];
        label.tag = 2016;
        label.font = KTitleFont;
        [headerView addSubview:label];
    }
    
    NSString *headText = [self titleForHeaderInSection:section];
    UILabel* label = [headerView viewWithTag:2016];
    label.text = headText;
    label.frame = CGRectMake(15, 0, SCREEN_WIDTH - 2 * 15, 35);
    return headerView;
}

- (NSString *)titleForHeaderInSection:(NSInteger)section{
    NSArray *temp = self.dataSource[section];
    YWReportTroubleModel* reportTrouble = temp.count ? temp[0] : nil;
    NSString *time = [YWCommonTool showChineseFormatterDate:reportTrouble.reportTime/1000];
    NSInteger weekDay = [NSDate dateWithTimeIntervalSince1970:reportTrouble.reportTime/1000].weekday;
    NSString *weekStr = [YWCommonTool weekDayString:weekDay-1];
    NSString * title = [NSString stringWithFormat:@"%@  %@",time,weekStr];
    return title;
}

- (void)refreshTop
{
    page = 1;
    [self.tableView.mj_footer resetNoMoreData];
    [self requestData:YWTableViewFreshTypeDown];
}

- (void)refreshFootor
{
    [self requestData:YWTableViewFreshTypeUp];
}

- (void)requestData:(YWTableViewFreshType)refreshType{
    YWWeakSelf(weakSelf);
    dispatch_group_t group = dispatch_group_create();
    dispatch_async(dispatch_get_global_queue(0, 0), ^{
        __block NSInteger dataCount = 0;
        if (refreshType == YWTableViewFreshTypeUp) {
            page++;
        }
        dispatch_group_enter(group);
        
        [[YWReportTroubleManager shareManager] requestMyReportTroubleWithPage:page pageSize:10 completeBlock:^(NSInteger count) {
            dataCount += count;
            dispatch_group_leave(group);
        }];
        
        dispatch_group_wait(group, DISPATCH_TIME_FOREVER);
        dispatch_async(dispatch_get_main_queue(), ^{
            if (refreshType == YWTableViewFreshTypeDown) {
                [weakSelf.tableView.mj_header endRefreshing];
            }
            else {
                [weakSelf.tableView.mj_footer endRefreshing];
            }
            
            weakSelf.dataSource = nil;
            [weakSelf.tableView reloadData];
        });
        if (dataCount>0) {
            NSTimeInterval currentTime = [[NSDate date] timeIntervalSince1970]*1000;
            [[YWEwinManager shareManager] saveLastReadTime:currentTime type:YWUnReadCountTypeTrouble];
        }
    });
}

- (void)dealloc{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end
